package com.business.student.controller;

import com.business.common.core.controller.BaseController;
import com.business.common.core.domain.AjaxResult;
import com.business.common.core.page.TableDataInfo;
import com.business.common.utils.SecurityUtils;
import com.business.common.utils.poi.ExcelUtil;
import com.business.exam.domain.ExamPaperAnswer;
import com.business.exam.domain.ExamPaperAnswerInfo;
import com.business.exam.domain.UserEventLog;
import com.business.exam.domain.exam.ExamPaperEditRequestVM;
import com.business.exam.event.CalculateExamPaperAnswerCompleteEvent;
import com.business.exam.event.UserEvent;
import com.business.exam.service.IExamPaperService;
import com.business.exam.utils.DateTimeUtil;
import com.business.exam.utils.ExamUtil;
import com.business.student.domain.ExamPaperAnswerPageResponseVM;
import com.business.student.domain.ExamPaperAnswerPageVM;
import com.business.student.domain.ExamPaperReadVM;
import com.business.student.domain.ExamPaperSubmitVM;
import com.business.student.service.IExamPaperAnswerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController("StudentExamPaperAnswerController")
@RequestMapping(value = "/api/student/exampaper/answer")
public class ExamPaperAnswerController extends BaseController {

    @Autowired
    private IExamPaperAnswerService examPaperAnswerService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private IExamPaperService examPaperService;

    @RequestMapping(value = "/pageList", method = RequestMethod.POST)
    public TableDataInfo pageList(@RequestBody @Valid ExamPaperAnswerPageVM model) {
        model.setCreateUser(SecurityUtils.getUserId());
        startPage();
        List<ExamPaperAnswer> resultList = examPaperAnswerService.studentPage(model);
        List<ExamPaperAnswerPageResponseVM> dataList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(e -> {
                ExamPaperAnswerPageResponseVM vm = new ExamPaperAnswerPageResponseVM();
                BeanUtils.copyProperties(e, vm);
                vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
                vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
                vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
                vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
                vm.setPassScore(ExamUtil.scoreToVM(e.getPassScore()));
                vm.setCreateTime(e.getCreateTime());
                dataList.add(vm);
            });
        }
        return getDataTable(dataList);
    }

    @RequestMapping(value = "/pageListForAdmin", method = RequestMethod.POST)
    public TableDataInfo pageListForAdmin(@RequestBody @Valid ExamPaperAnswerPageVM model) {
        model.setCreateUser(SecurityUtils.getUserId());
        startPage();
        List<ExamPaperAnswer> resultList = examPaperAnswerService.studentPageForAdmin(model);
        List<ExamPaperAnswerPageResponseVM> dataList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(e -> {
                ExamPaperAnswerPageResponseVM vm = new ExamPaperAnswerPageResponseVM();
                BeanUtils.copyProperties(e, vm);
                vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
                vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
                vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
                vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
                vm.setPassScore(ExamUtil.scoreToVM(e.getPassScore()));
                vm.setPassStatus(e.getPassStatus());
                vm.setCreateTime(e.getCreateTime());
                dataList.add(vm);
            });
        }
        return getDataTable(dataList);
    }

    @RequestMapping(value = "/answerSubmit", method = RequestMethod.POST)
    public AjaxResult answerSubmit(@RequestBody ExamPaperSubmitVM examPaperSubmitVM) {
        ExamPaperAnswerInfo examPaperAnswerInfo = examPaperAnswerService.calculateExamPaperAnswer(examPaperSubmitVM);
        if (null == examPaperAnswerInfo) {
            return AjaxResult.error(2, "试卷不能重复做");
        }
        ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
        Integer userScore = examPaperAnswer.getUserScore();
        String scoreVm = ExamUtil.scoreToVM(userScore);
        UserEventLog userEventLog = new UserEventLog(SecurityUtils.getUserId().intValue(), SecurityUtils.getUsername(), SecurityUtils.getUsername(), new Date());
        String content = SecurityUtils.getUsername() + " 提交试卷：" + examPaperAnswerInfo.getExamPaper().getName()
                + " 得分：" + scoreVm
                + " 耗时：" + ExamUtil.secondToVM(examPaperAnswer.getDoTime());
        userEventLog.setContent(content);

        //eventPublisher.publishEvent(new CalculateExamPaperAnswerCompleteEvent(examPaperAnswerInfo));
        // eventPublisher.publishEvent(new UserEvent(userEventLog));
        return AjaxResult.success("操作成功!", scoreVm);
    }

/*

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse edit(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM) {
        boolean notJudge = examPaperSubmitVM.getAnswerItems().stream().anyMatch(i -> i.getDoRight() == null && i.getScore() == null);
        if (notJudge) {
            return RestResponse.fail(2, "有未批改题目");
        }

        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(examPaperSubmitVM.getId());
        ExamPaperAnswerStatusEnum examPaperAnswerStatusEnum = ExamPaperAnswerStatusEnum.fromCode(examPaperAnswer.getStatus());
        if (examPaperAnswerStatusEnum == ExamPaperAnswerStatusEnum.Complete) {
            return RestResponse.fail(3, "试卷已完成");
        }
        String score = examPaperAnswerService.judge(examPaperSubmitVM);
        User user = getCurrentUser();
        UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
        String content = user.getUserName() + " 批改试卷：" + examPaperAnswer.getPaperName() + " 得分：" + score;
        userEventLog.setContent(content);
        eventPublisher.publishEvent(new UserEvent(userEventLog));
        return RestResponse.ok(score);
    }
*/

    /**
     * 查看试卷
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/read/{id}", method = RequestMethod.POST)
    public AjaxResult read(@PathVariable Integer id) {
        ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(id);
        ExamPaperReadVM vm = new ExamPaperReadVM();
        ExamPaperEditRequestVM paper = examPaperService.examPaperToVM(examPaperAnswer.getExamPaperId());
        ExamPaperSubmitVM answer = examPaperAnswerService.examPaperAnswerToVM(examPaperAnswer.getId());
        vm.setPaper(paper);
        vm.setAnswer(answer);
        return AjaxResult.success(vm);
    }



    @PostMapping("/export")
    public void export(HttpServletResponse response,  ExamPaperAnswerPageVM model) {
        model.setCreateUser(SecurityUtils.getUserId());
        List<ExamPaperAnswer> resultList = examPaperAnswerService.studentPageForAdmin(model);
        List<ExamPaperAnswerPageResponseVM> dataList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(e -> {
                ExamPaperAnswerPageResponseVM vm = new ExamPaperAnswerPageResponseVM();
                BeanUtils.copyProperties(e, vm);
                vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
                vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
                vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
                vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
                vm.setPassScore(ExamUtil.scoreToVM(e.getPassScore()));
                vm.setCreateTime(e.getCreateTime());
                dataList.add(vm);
            });
        }
        ExcelUtil<ExamPaperAnswerPageResponseVM> util = new ExcelUtil<ExamPaperAnswerPageResponseVM>(ExamPaperAnswerPageResponseVM.class);
        util.exportExcel(response, dataList, "考试记录");
    }


    @RequestMapping(value = "/findAnswerCount", method = RequestMethod.POST)
    public AjaxResult findAnswerCount(@RequestBody String id) {
        return examPaperAnswerService.findUserAnswerCount(id);
    }
}
